package com.mf.security.handler;

import com.mf.basic.BasicKey;
import io.github.heollhai.common.config.reids.RedisOperator;
import io.github.heollhai.common.config.security.utils.SecurityUtils;
import io.github.heollhai.common.entity.security.dto.UserByRoleDto;
import io.github.heollhai.common.result.Result;
import io.github.heollhai.common.utils.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

/**
 * @Author: lmf
 * @Create: 2024/8/6 15:04
 * Description:退出登录相关处理
 */
@Component
public class LogoutHandlerImpl implements LogoutHandler {
    @Resource
    private RedisOperator redisOperator;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {


        if (VerifyUtils.isEmpty(authentication)) {
            // 返回前端信息
            Result<String> result = Result.success("退出登录成功");
            ResponseUtils.writeJson(response, result);
        } else {

            UserByRoleDto userByRoleDto = SecurityUtils.getUserByRoleDto();
            if (VerifyUtils.isNotEmpty(userByRoleDto)) {
                String token = request.getHeader(BasicKey.HEADER_TOKEN);
                if (StringUtils.isNotBlank(token)) {
                    String _token = JWTUtil.checkJwt(token);

                    String browserInfo = HttpServletRequestUtils.getBrowserInfo(request, BasicKey.REDIS_USER_TOKEN);
                    // 根据token删除用户登录信息  公共信息不删除等待自动过期 (删除登录信息后无法再直接获取公共信息,但是该账号其他登录的token不受影响 同一ip下的会被清除掉登录信息)
                    redisOperator.delete(browserInfo + _token);

                    // 返回前端信息
                    Result<String> result = Result.success("退出登录成功");
                    ResponseUtils.writeJson(response, result);
                }
            }
        }


    }
}
